<template>
  <div class="deviceCategory-add-update-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      :title="!modelValue.form.id ? `新增机台产品` : `修改机台产品`"
      width="750px"
    >
      <div style="padding-right: 50px; padding-top: 20px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="addEditRef"
          :label-width="100"
        >
          <div class="form-item" style="align-items: flex-start">
            <div>
              <el-form-item label="产品编码" prop="number">
                <el-input
                  style="width: 240px"
                  placeholder="请输入类型编码"
                  v-model="modelValue.form.number"
                  autocomplete="off"
                  :disabled="modelValue.form.id"
                />
              </el-form-item>
               <el-form-item label="SPU分类" prop="name">
                  <el-select
                    style="width: 240px"
                    v-model="modelValue.form.categoryId"
                    placeholder="选择SPU分类"
                  >
                    <el-option
                      v-for="option in modelValue.productCategoryList"
                      :key="option.id"
                      :label="option.name"
                      :value="option.id"
                    />
                  </el-select>
              </el-form-item>
              <el-form-item label="SPU名称" prop="name">
                <el-input
                  style="width: 240px"
                  placeholder="请输入SPU名称"
                  v-model="modelValue.form.name"
                  autocomplete="off"
                />
              </el-form-item>

            </div>
            <el-form-item label="产品图片" prop="url">
              <div style="width: 240px">
                <el-upload
                  class="avatar-uploader"
                  ref="uploadRef"
                  :before-upload="canUpload"
                  :on-success="uploadSuccess"
                  :on-error="uploadError"
                  :http-request="handleFileChange"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                >
                   <div slot="file" slot-scope="{file}">
                    <img
                      v-if="modelValue.form.url"
                      :src="modelValue.form.url"
                      class="avatar"
                    >
                      <span
                          class="el-upload-list__item-delete"
                          @click="modelValue.form.url = ''"
                        >
                          <i class="el-icon-delete"></i>
                        </span>
                    </img>
                    <el-icon v-if="!modelValue.form.url" class="avatar-uploader-icon"
                      ><Plus
                    /></el-icon>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </div>


          <!-- productCategoryList -->
          <div class="form-item" style="align-items: flex-start">
             <el-form-item label="产品品牌" prop="brandName">
                <el-input
                  style="width: 240px"
                  placeholder="请输入产品品牌"
                  v-model="modelValue.form.brandName"
                  autocomplete="off"
                />
              </el-form-item>
            <el-form-item label="产品型号" prop="model">
              <el-input
                style="width: 240px"
                placeholder="请输入产品型号"
                v-model="modelValue.form.model"
                autocomplete="off"
              />
            </el-form-item>

          </div>

           <div class="form-item" style="align-items: flex-start">
             <el-form-item label="产品重量" prop="weight">
              <el-input
                style="width: 240px"
                placeholder="请输入产品重量"
                v-model="modelValue.form.weight"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="产品功能" prop="func">
              <!-- <el-input
                style="width: 240px"
                placeholder="请输入产品功能"
                v-model="modelValue.form.func"
                autocomplete="off"
              /> -->

                <el-select
                    style="width: 240px"
                    v-model="modelValue.form.func"
                    placeholder="选择产品功能"
                  >
                    <el-option
                      v-for="option in funcOptions"
                      :key="option.id"
                      :label="option.name"
                      :value="option.id"
                    />
                  </el-select>
            </el-form-item>
          </div>
          <div class="form-item" style="align-items: flex-start">
             <el-form-item label="产品尺寸" prop="size">
              <el-input
                style="width: 240px"
                placeholder="请输入产品尺寸"
                v-model="modelValue.form.size"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="产品容量" prop="capacity">
              <el-input
                style="width: 240px"
                placeholder="请输入产品容量"
                v-model="modelValue.form.capacity"
                autocomplete="off"
              />
            </el-form-item>

          </div>

          <div class="form-item" style="align-items: flex-start">
             <el-form-item label="产品重量" prop="weight">
              <el-input
                style="width: 240px"
                placeholder="请输入产品重量"
                v-model="modelValue.form.weight"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="产品功能" prop="func">
                 <el-select
                    style="width: 240px"
                    v-model="modelValue.form.func"
                    placeholder="选择产品功能"
                  >
                    <el-option
                      v-for="option in [{
                        id: '1',
                        name: `全自动`
                      }]"
                      :key="option.id"
                      :label="option.name"
                      :value="option.id"
                    />
                  </el-select>
            </el-form-item>

          </div>
           <el-form-item label="备注" prop="mark">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
                v-model="modelValue.form.mark"
                autocomplete="off"
              />
            </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!modelValue.form.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ensure"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import OSS from "ali-oss";
import { Plus } from "@element-plus/icons-vue";
import {
  addDeviceCategory,
  updateDeviceCategory,
} from "@/api/dms-device-category.api";

const props = defineProps(["modelValue"]);

const funcOptions = [
  {
    id: "1",
    name: "全自动"
  },
  {
    id: "2",
    name: "半自动"
  },
  {
    id: "3",
    name: "手动"
  }
]


// OSS客户端配置
const ossClient = new OSS({
  region: "oss-cn-shenzhen",
  accessKeyId: "LTAI5t741H6okseZdRMDhe9U",
  accessKeySecret: "dz8VyL0oQa6xPIge8kfzPBQbpM1ZKQ",
  bucket: "yunhaiwuxian",
});

const uploadRef = ref();
const addEditRef = ref<FormInstance>();
const canUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPng = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPng) {
    ElMessage({
      message: "上传头像图片只能是 JPG/PNG 格式!",
      type: "error",
    });
    return false;
  }
  if (!isLt2M) {
    ElMessage({
      message: "上传头像图片大小不能超过 2MB!",
      type: "error",
    });
    return false;
  }
  return true;
};

const handleFileChange = async (event: any) => {
  // console.log('当前文件:', file) // 关键：获取原始文件对象
  let file = event.file;
  try {
    const fileName = `mengze-test/images/${Date.now()}_${file.name}`;
    const res = await ossClient.put(fileName, file);
    console.log("上传内容:", res);
    props.modelValue.form.url = res.url;
    // props.modelValue.form.fileList.push({
    //   uid: file.uid,
    //   name: file.name,
    //   url: res.url,
    // })

    // insertFn(res.url, file.name, res.url)
  } catch (err) {
    console.error("上传失败:", err);
  }
};

const uploadHeaders = {
  token: localStorage.getItem("TOKEN"),
};

const uploadError = (err, file, fileList) => {
  ElMessage({
    message: err.msg || err,
    type: "error",
  });
};

const uploadSuccess = (response, file, fileList) => {
  ElMessage({
    message: "图片上传成功",
    type: "success",
  });
  return;
};

/***
 * 确认弹框
 */
const ensure = () => {
  let form = props.modelValue.form;
  let formData = {
    number: form.number,
    name: form.name,
    url: form.url,
    brandName: form.brandName,
    model: form.model,
    size: form.size,
    capacity: form.capacity,
    categoryId: form.categoryId,
    mark: form.mark,
    func: "全自动",
    weight: form.weight,
  };

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (form.id) {
        updateDeviceCategory({
          ...formData,
          id: form.id,
        })
          .then((res) => {
            cancel();
            ElMessage({
              message: props.modelValue.title + "修改成功",
              type: "success",
            });
            if (props.modelValue.refreshDataList) {
              props.modelValue.refreshDataList();
            }
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: "error",
            });
          });
        return;
      }

      addDeviceCategory(formData)
        .then((res) => {
          cancel();
          ElMessage({
            message: props.modelValue.title + "新增成功",
            type: "success",
          });
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList();
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: "error",
          });
        });
    }
  });
};

/***
 * 取消弹框
 */
const cancel = () => {
  props.modelValue.visible = false;
};
</script>
<style lang="scss" scoped>
.form-item {
  display: flex;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  display: block;
  border: 1px dashed #ccc;
  line-height: 128px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
  border: 1px dashed #ccc;
}

.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
  border: 1px dashed #ccc;
}
</style>
